const constant = require("../utils/constant");
const jwt = require("jsonwebtoken");
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware~");
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    const error = new Error(constant.UNAUTHORIZATION);
    return ctx.app.emit("error", error, ctx);
  }
  const token = authorization.replace("Bearer ", "");
  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, constant.TOKEN_KEY);
    // 把username放ctx全局使用
    ctx._id = result._id;
    console.log("jwt verify", result);
    await next();
  } catch (err) {
    console.dir(err.message);
    let error = {};
    console.log("auth", err);
    console.log("message", err.message);
    // console.log("21", err.__proto__.constructor.name);
    if (err.message.includes("jwt") || err.message.includes("token")) {
      error = new Error("登录失效，请重新登录");
      ctx.jwtErrorCode = constant.JWT_ERR;
    } else {
      error = new Error(err.message);
    }
    return ctx.app.emit("error", error, ctx);
  }
};
module.exports = verifyAuth;
